// pages/main/app-category/app-category.js
Page({
  data: {
    appInfo: {},
    categories: [],
    loading: true
  },

  onLoad(options) {
    console.log('应用分类页面参数:', options);
    // 获取应用信息
    const appId = options.appId;
    const appName = options.appName ? decodeURIComponent(options.appName) : '应用分类';
    this.setData({
      appInfo: {
        id: appId,
        name: appName,
        color: options.color || '#007aff',
      }
    });
    
    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: appName
    });
    
    // 加载分类数据
    this.loadCategories(appId);
  },

  // 加载分类数据
  loadCategories(appId) {
    this.setData({ loading: true });
    wx.request({
      url: `${getApp().globalData.serverUrl}/GetAppCategories/`,
      method: 'POST',
      data: {
        app_id: appId
      },
      success: (res) => {
        if (res.data.status) {
          this.setData({
            categories: res.data.categories || [],
            loading: false
          });
        } else {
          wx.showToast({
            title: res.data.message || '获取分类失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      },
      fail: (err) => {
        console.error('获取分类失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    });
  },

  // 点击小分类
  onSubCategoryTap(e) {
    const category = e.currentTarget.dataset.category;
    const subCategory = e.currentTarget.dataset.subCategory;
    console.log('点击小分类:', category, subCategory);
    const appId = this.data.appInfo.id;
    const appName = this.data.appInfo.name;
    const isApply = (id) => typeof id === 'string' && (id === 'apply_new' || id === 'apply_workorder');
    const isRecord = (id) => typeof id === 'string' && (id === 'apply_record' || id.endsWith('_record'));
    const isPending = (id) => typeof id === 'string' && (id === 'process_pending' || id.includes('pending'));
    const isHistory = (id) => typeof id === 'string' && (id.includes('audited') || id.includes('processed') || (id.endsWith('_record') && id !== 'apply_record'));

    // 工单管理优先处理
    if (this.data.appInfo.id === '66') {
      const workorderPageMap = {
        'apply_workorder': '/pages/main/workorder/apply-workorder/apply-workorder',
        'apply_record': '/pages/main/workorder/apply-record/apply-record',
        'process_workorder': '/pages/main/workorder/process-workorder/process-workorder',
        'process_record': '/pages/main/workorder/process-record/process-record'
      };
      const targetPage = workorderPageMap[subCategory.id];
      if (targetPage) {
        wx.navigateTo({ url: targetPage });
        return;
      }
    }
    if (isApply(subCategory.id)) {
      wx.navigateTo({
        url: `/pages/main/common-apply/common-apply?appId=${appId}&appName=${encodeURIComponent(appName)}&categoryId=${category.id}&categoryName=${encodeURIComponent(category.name)}&subCategoryId=${subCategory.id}&subCategoryName=${encodeURIComponent(subCategory.name)}`
      });
      return;
    }
    if (isPending(subCategory.id)) {
      wx.navigateTo({
        url: `/pages/main/common-pending-list/common-pending-list?appId=${appId}&appName=${encodeURIComponent(appName)}`
      });
      return;
    }
    if (isRecord(subCategory.id)) {
      wx.navigateTo({
        url: `/pages/main/common-record-list/common-record-list?appId=${appId}&appName=${encodeURIComponent(appName)}`
      });
      return;
    }
    if (isHistory(subCategory.id)) {
      wx.navigateTo({
        url: `/pages/main/common-history-list/common-history-list?appId=${appId}&appName=${encodeURIComponent(appName)}`
      });
      return;
    }
    
    // 对于工单管理（app_id == '66'）的四个页面，跳转到对应的工单管理页面
    if (this.data.appInfo.id === '66') {
      const workorderPageMap = {
        'apply_record': '/pages/main/workorder/apply-record/apply-record',
        'process_workorder': '/pages/main/workorder/process-workorder/process-workorder',
        'process_record': '/pages/main/workorder/process-record/process-record'
      };

      const targetPage = workorderPageMap[subCategory.id];
      if (targetPage) {
        wx.navigateTo({
          url: targetPage,
          fail: (err) => {
            console.error('跳转失败:', err);
            wx.showToast({
              title: '页面跳转失败',
              icon: 'none'
            });
          }
        });
        return;
      }
    }
    
    // 对于经纪业务（app_id == '26'）的待提交审核类的三个页面，跳转到专门的待提交页面
    if (this.data.appInfo.id === '26' && category.id === 'pending_submit') {
      const typeMap = {
        'receive_pending_submit': 'receive',
        'payment_pending_submit': 'payment',
        'refund_pending_submit': 'refund'
      };
      const submitType = typeMap[subCategory.id] || 'receive';
      
      wx.navigateTo({
        url: `/pages/main/pending-submit/pending-submit?appId=${this.data.appInfo.id}&appName=${encodeURIComponent(this.data.appInfo.name)}&categoryId=${category.id}&categoryName=${encodeURIComponent(category.name)}&subCategoryId=${subCategory.id}&subCategoryName=${encodeURIComponent(subCategory.name)}&type=${submitType}`
      });
      return;
    }
    
    // 其他情况（包括汇总表一览表）跳转到对应的app-center页面
    wx.navigateTo({
      url: `/pages/main/app-center/app-center?appId=${this.data.appInfo.id}&appName=${encodeURIComponent(this.data.appInfo.name)}&categoryId=${category.id}&categoryName=${encodeURIComponent(category.name)}&subCategoryId=${subCategory.id}&subCategoryName=${encodeURIComponent(subCategory.name)}`
    });
  }
});
